package parser;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

/**
 * Cette classe parcourt du HTML avec SAX
 *
 */
public class HTMLHandler implements ContentHandler
{
	private StringBuilder stringBuilder;
	private WordsHandler wordsHander;
	
	public HTMLHandler(WordsHandler wordsHander)
	{
		this.wordsHander = wordsHander;
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException
	{
		stringBuilder.append(ch, start, length);
		return;
	}

	@Override
	public void endDocument() throws SAXException
	{
		stringBuilder = null;
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException
	{
		fireWords();
		//TODO style
	}

	@Override
	public void endPrefixMapping(String prefix) throws SAXException
	{

	}

	@Override
	public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException
	{

	}

	@Override
	public void processingInstruction(String target, String data) throws SAXException
	{

	}

	@Override
	public void setDocumentLocator(Locator locator)
	{

	}

	@Override
	public void skippedEntity(String name) throws SAXException
	{

	}

	@Override
	public void startDocument() throws SAXException
	{
		stringBuilder = new StringBuilder();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException
	{
		fireWords();
		//TODO style
	}

	@Override
	public void startPrefixMapping(String prefix, String uri) throws SAXException
	{

	}
	
	private void fireWords()
	{
		Iterable<String> words = WordsSpliter.getInstance().split(stringBuilder.toString());
		for (String word : words)
		{
			wordsHander.handle(new FormatedWord(word)); //TODO style
		}
		stringBuilder.delete(0, stringBuilder.length());
	}
}
